<%@ page language="java" import="com.alibaba.fastjson.JSONArray" pageEncoding="UTF-8" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="okhttp3.*" %>
<%@ page import="org.w3c.dom.Document" %>
<%@ page import="org.w3c.dom.Element" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.docs.docs.util.DesUtils" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="javax.xml.parsers.DocumentBuilder" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
<%@ page import="javax.xml.transform.OutputKeys" %>
<%@ page import="javax.xml.transform.Transformer" %>
<%@ page import="javax.xml.transform.TransformerFactory" %>
<%@ page import="javax.xml.transform.dom.DOMSource" %>
<%@ page import="javax.xml.transform.stream.StreamResult" %>
<%@ page import="java.io.StringWriter" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.concurrent.TimeUnit" %>
<%--收文流程调用档案管理系统预归档库接口--%>
<%
    String requestid = Util.null2String(request.getParameter("requestid"));
    String tablename = "formtable_main_60";
    String requestname = "发文测试-2024-06-13-test";
    out.print(">>>>>WeaSwsqlcAction>>>>>requestid=" + requestid + "<br/>");
    try {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from " + tablename + " where requestid=?", requestid);
        rs.next();
        //盖章合同文件
        String pdfwj = Util.null2String(rs.getString("pdfwj"));
        //责任者
        String zrz = Util.null2String(rs.getString("zrz"));
        //保管期限
        String bgqx = Util.null2String(rs.getString("bgqx"));
        //登记日期
        String djrq = Util.null2String(rs.getString("djrq"));
        //成文日期
        String cwrq = Util.null2String(rs.getString("cwrq"));
        //页数
        String ys = Util.null2String(rs.getString("ys"));
        //密级
        String mj = Util.null2String(rs.getString("mj"));
        //解密划控
        String jmhk = Util.null2String(rs.getString("jmhk"));
        //qfr
        String qfr2 = Util.null2String(rs.getString("qfr2"));
        //文件编号
        String wjbh = Util.null2String(rs.getString("wjbh"), " ");
        //机构代码
        String jgdm2 = Util.null2String(rs.getString("jgdm2"));

        JSONObject paramsJson = new JSONObject();
        JSONArray datasList = new JSONArray();
        JSONObject datasJson = new JSONObject();
        JSONObject arcJson = new JSONObject();
        arcJson.put("appId", "xbivbhbzz2");
        JSONArray filesList = new JSONArray();
        JSONObject filesJson = new JSONObject();
        JSONArray documentList = new JSONArray();
        if (!pdfwj.isEmpty()) {
            String[] pdfwjArr = pdfwj.split(",");
            for (int i = 0; i < pdfwjArr.length; i++) {
                JSONObject documentJson = new JSONObject();
                documentJson.put("needDownLoad", "true");
                documentJson.put("ftpName", "");
                JSONArray paramList = new JSONArray();
                Map<String, Object> imagefileInfo = getImagefileInfo(pdfwjArr[i]);
                JSONObject paramJson1 = new JSONObject();
                JSONObject paramJson2 = new JSONObject();
                String imagefileid = Util.null2String(imagefileInfo.get("imagefileid"));
                String ddcode = getTokenKey(imagefileid);
                String fileDownload = "http://36.156.144.9:8088/weaver/weaver.file.FileDownload?fileid=" + imagefileid + "&download=1&ddcode=" + ddcode;
                paramJson1.put("name", "path");
                paramJson1.put("title", "附件地址");
                paramJson1.put("content", fileDownload);
                paramJson2.put("name", "arc_document_name");
                paramJson2.put("title", "附件名称");
                paramJson2.put("content", Util.null2String(imagefileInfo.get("imagefilename")));
                paramList.add(paramJson1);
                paramList.add(paramJson2);
                documentJson.put("param", paramList);
                documentList.add(documentJson);
            }
        }
        filesJson.put("document", documentList);
        JSONObject metadataJson = new JSONObject();
        metadataJson.put("type", "2");
        JSONArray fieldList = new JSONArray();
        JSONObject owner_deptJson = new JSONObject();
        owner_deptJson.put("name", "owner_dept");
        owner_deptJson.put("title", "所属部门");
        owner_deptJson.put("content", "1");
        fieldList.add(owner_deptJson);
        JSONObject bgqxJson = new JSONObject();
        bgqxJson.put("name", "bgqx");
        bgqxJson.put("title", "保管期限");
        bgqxJson.put("content", bgqx);
        fieldList.add(bgqxJson);
        JSONObject ssfbJson = new JSONObject();
        ssfbJson.put("name", "owner_company");
        ssfbJson.put("title", "所属分部");
        ssfbJson.put("content", "1");
        fieldList.add(ssfbJson);
        JSONObject zrzJson = new JSONObject();
        zrzJson.put("name", "zrz");
        zrzJson.put("title", "责任者");
        zrzJson.put("content", zrz);
        fieldList.add(zrzJson);
        JSONObject dzywidJson = new JSONObject();
        dzywidJson.put("name", "owner_id");
        dzywidJson.put("title", "电子原文id");
        dzywidJson.put("content", "1");
        fieldList.add(dzywidJson);
        JSONObject kfqkJson = new JSONObject();
        kfqkJson.put("name", "kfqk");
        kfqkJson.put("title", "开放情况");
        kfqkJson.put("content", jmhk);
        fieldList.add(kfqkJson);
        JSONObject djrqJson = new JSONObject();
        djrqJson.put("name", "djrq");
        djrqJson.put("title", "登记日期");
        djrqJson.put("content", djrq);
        fieldList.add(djrqJson);
        JSONObject wjbhJson = new JSONObject();
        wjbhJson.put("name", "wjbh");
        wjbhJson.put("title", "文件编号");
        wjbhJson.put("content", wjbh + " ");
        fieldList.add(wjbhJson);
        JSONObject ssryJson = new JSONObject();
        ssryJson.put("name", "owner_user");
        ssryJson.put("title", "所属人员");
        ssryJson.put("content", "1");
        fieldList.add(ssryJson);
        JSONObject lssjidJson = new JSONObject();
        lssjidJson.put("name", "form_biz_id_old");
        lssjidJson.put("title", "历史数据id");
        lssjidJson.put("content", "1");
        fieldList.add(lssjidJson);
        JSONObject btJson = new JSONObject();
        btJson.put("name", "bt");
        btJson.put("title", "标题");
        btJson.put("content", requestname);
        fieldList.add(btJson);
        JSONObject jgdmJson = new JSONObject();
        jgdmJson.put("name", "jgdm");
        jgdmJson.put("title", "机构代码");
        jgdmJson.put("content", jgdm2);
        fieldList.add(jgdmJson);
        JSONObject fjscJson = new JSONObject();
        fjscJson.put("name", "arc_document");
        fjscJson.put("title", "附件上传");
        fjscJson.put("content", " ");
        fieldList.add(fjscJson);
        JSONObject sjlxJson = new JSONObject();
        sjlxJson.put("name", "data_type");
        sjlxJson.put("title", "数据类型");
        sjlxJson.put("content", "0");
        fieldList.add(sjlxJson);
        JSONObject gldjJson = new JSONObject();
        gldjJson.put("name", "relationNums");
        gldjJson.put("title", "关联单据");
        gldjJson.put("content", "1");
        fieldList.add(gldjJson);
        JSONObject ysJson = new JSONObject();
        ysJson.put("name", "ys");
        ysJson.put("title", "页数");
        ysJson.put("content", ys);
        fieldList.add(ysJson);
        JSONObject qfrJson = new JSONObject();
        qfrJson.put("name", "qfr");
        qfrJson.put("title", "签发人");
        qfrJson.put("content", qfr2);
        fieldList.add(qfrJson);
        JSONObject cwrqJson = new JSONObject();
        cwrqJson.put("name", "cwrq");
        cwrqJson.put("title", "成文日期");
        cwrqJson.put("content", cwrq);
        fieldList.add(cwrqJson);
        JSONObject mjJson = new JSONObject();
        mjJson.put("name", "mj");
        mjJson.put("title", "密级");
        mjJson.put("content", mj);
        fieldList.add(mjJson);
        JSONObject qzhJson = new JSONObject();
        qzhJson.put("name", "qzh");
        qzhJson.put("title", "全宗号");
        qzhJson.put("content", "E066");
        fieldList.add(qzhJson);
        metadataJson.put("field", fieldList);
        filesJson.put("metadata", metadataJson);
        filesList.add(filesJson);
        datasJson.put("arc", arcJson);
        datasJson.put("files", filesList);
        datasList.add(datasJson);
        paramsJson.put("datas", datasList);
        out.print(">>>>WeaHtspbsqlcAction>>>>paramsJson=" + paramsJson + "<br/>");
        String apiUrl = "http://36.150.170.5:8088/api/archive/base/recieveData";
        JSONObject resultJson = sendOKHttpRequesttoJSON(apiUrl, paramsJson.toJSONString());
        out.print(">>>>WeaHtspbsqlcAction>>>>resultJson=" + resultJson);

    } catch (Exception e) {
        out.print(">>>>>WeaHtspbsqlcAction>>>>>Exception=" + e);
    }

%>
<%!
    private static BaseBean baseBean = new BaseBean();

    //档案目录封装
    public static String archiveToXml(List<Map<String, String>> fileList, List<Map<String, String>> metadataList) {
        String xmlString = "";
        baseBean.writeLog(">>>>>archiveToXml>>>>>fileList=" + fileList);
        baseBean.writeLog(">>>>>archiveToXml>>>>>metadataList=" + metadataList);
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            Element datas_element = document.createElement("datas");
            document.appendChild(datas_element);
            Element data_element = document.createElement("data");
            datas_element.appendChild(data_element);
            Element arc_element = document.createElement("arc");
            arc_element.setAttribute("appId", "xbivbhbzz2");
            arc_element.appendChild(document.createTextNode(" "));
            data_element.appendChild(arc_element);
            Element files_element = document.createElement("files");
            data_element.appendChild(files_element);
            Element file_element = document.createElement("file");
            files_element.appendChild(file_element);
            for (Map<String, String> fileMap : fileList) {
                Element document_element = document.createElement("document");
                document_element.setAttribute("ftpName", "");
                document_element.setAttribute("needDownLoad", "true");
                Element filename_param_element = document.createElement("param");
                filename_param_element.setAttribute("name", "arc_document_name");
                filename_param_element.setAttribute("title", "文件名称");
                filename_param_element.appendChild(document.createTextNode(fileMap.get("filename")));
                document_element.appendChild(filename_param_element);
                Element filepath_param_element = document.createElement("param");
                filepath_param_element.setAttribute("name", "path");
                filepath_param_element.setAttribute("title", "文件路径");
                filepath_param_element.appendChild(document.createTextNode(fileMap.get("filepath")));
                document_element.appendChild(filepath_param_element);
                file_element.appendChild(document_element);
            }
            Element metadata_element = document.createElement("metadata");
            metadata_element.setAttribute("type", "uf_arc_htspb");
            metadata_element.setAttribute("uniqueK", "code");
            metadata_element.setAttribute("uniqueV", getTimestamp());
            for (Map<String, String> metadataMap : metadataList) {
                Element field_element = document.createElement("field");
                field_element.setAttribute("name", metadataMap.get("name"));
                field_element.setAttribute("title", metadataMap.get("title"));
                field_element.appendChild(document.createTextNode(metadataMap.get("value")));
                metadata_element.appendChild(field_element);
            }
            file_element.appendChild(metadata_element);


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new StringWriter());
            transformer.transform(source, result);
            xmlString = result.getWriter().toString();
            baseBean.writeLog(">>>>>archiveToXml>>>>>xmlString=" + xmlString);
        } catch (Exception e) {
            baseBean.writeLog(">>>>>archiveToXml>>>>>Exception e:" + e.getMessage(), e);
        }
        return xmlString;
    }

    /**
     * 发送请求
     *
     * @param url
     * @return
     */
    public static JSONObject sendOKHttpRequesttoXML(String url) {
        baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>url=" + url);
        JSONObject resultJson = new JSONObject();
        String message = "";
        String data = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .build();
            Response response = client.newCall(request).execute();
            baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>response=" + response);
            String result = Util.null2String(response.body().string());
            baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>result=" + result);
            if (!"".equals(result)) {
                data = result;
                message = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>Exception=" + e.getMessage(), e);
        }
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 发送请求
     *
     * @param url
     * @return
     */
    public static JSONObject sendOKHttpRequesttoJSON(String url, String params) {
        baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>url=" + url);
        JSONObject resultJson = new JSONObject();
        String message = "";
        String data = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .build();
            Response response = client.newCall(request).execute();
            baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>response=" + response);
            String result = Util.null2String(response.body().string());
            baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>result=" + result);
            if (!"".equals(result)) {
                data = result;
                message = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>Exception=" + e.getMessage(), e);
        }
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }


    //根据文档ID获取附件信息
    public static Map<String, Object> getImagefileInfo(String docid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select t1.imagefileid,t1.imagefilename,t1.imagefiletype,t1.filesize,t2.operatedate,t2.operatetime \n" +
                "from imagefile t1 join docimagefile t2 on t1.imagefileid=t2.imagefileid where t2.docid=?", docid);
        rs.next();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("imagefileid", Util.null2String(rs.getString("imagefileid")));
        resultMap.put("operatedate", Util.null2String(rs.getString("operatedate")));
        resultMap.put("operatetime", Util.null2String(rs.getString("operatetime")));
        resultMap.put("imagefilename", Util.null2String(rs.getString("imagefilename")));
        resultMap.put("imagefiletype", Util.null2String(rs.getString("imagefiletype")));
        resultMap.put("filesize", Util.null2String(rs.getString("filesize")));
        return resultMap;
    }

    //
    public static String getTokenKey(String imagefileid) {
        String ddcode = 1 + "_" + imagefileid;
        DesUtils des = null;
        try {
            des = new DesUtils();
            ddcode = des.encrypt(ddcode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ddcode;
    }

    public static String getTimestamp() {
        return String.format("%015d", System.currentTimeMillis());
    }

%>